<template>
  <view>
    <view class="uni-header">
      <view class="uni-group">
        <view class="uni-title"></view>
        <view class="uni-sub-title"></view>
      </view>
      <view class="uni-group">
        <input class="uni-search" type="text" v-model="query" @confirm="search" placeholder="请输入搜索内容" />
        <button class="uni-button" type="default" size="mini" @click="search">搜索</button>
        <button class="uni-button" type="default" size="mini" @click="navigateTo('./add')">新增</button>
        <button class="uni-button" type="default" size="mini" :disabled="!selectedIndexs.length" @click="delTable">批量删除</button>
        <download-excel class="hide-on-phone" :fields="exportExcel.fields" :data="exportExcelData" :type="exportExcel.type" :name="exportExcel.filename">
          <button class="uni-button" type="primary" size="mini">导出 Excel</button>
        </download-excel>
      </view>
    </view>
    <uni-popup ref="previewPopup" type="dialog">
      <view class="preview-popup">
        <swiper class="preview-swiper" :current="currentPreviewIndex" @change="handleSwiperChange">
          <swiper-item v-for="(img, index) in previewImages" :key="index">
            <image :src="img" mode="aspectFit" class="preview-image" />
          </swiper-item>
        </swiper>
        <button class="uni-button" type="default" @click="closePreview">关闭</button>
      </view>
    </uni-popup>
    <view class="uni-container">
      <unicloud-db ref="udb" 
        collection="a-tasks"
        field="_id,template_id,photo_count,photos,result_images,gif_url,create_date,operator_id" 
        :where="where"
        :getone="false"
        page-data="replace"
        :orderby="orderby" 
        :getcount="true" 
        :page-size="options.pageSize" 
        :page-current="options.pageCurrent"
        v-slot:default="{data,pagination,loading,error,options}" 
        :options="options" 
        loadtime="manual" 
        @load="onqueryload">
        <uni-table ref="table" :loading="loading" :emptyText="error.message || '没有更多数据'" border stripe type="selection" @selection-change="selectionChange">
          <uni-tr>
            <uni-th align="center" sortable @sort-change="sortChange($event, '_id')">任务编号</uni-th>
            <uni-th align="center" sortable @sort-change="sortChange($event, 'create_date')" filter-type="timestamp" @filter-change="filterChange($event, 'create_date')">创建时间</uni-th>
            <uni-th align="center" sortable @sort-change="sortChange($event, 'template_id')">使用模板</uni-th>
            <uni-th align="center" sortable @sort-change="sortChange($event, 'photo_count')" filter-type="range" @filter-change="filterChange($event, 'photo_count')">图片数量</uni-th>
            <uni-th align="center" sortable @sort-change="sortChange($event, 'photos')">拍摄照片</uni-th>
            <uni-th align="center" sortable @sort-change="sortChange($event, 'result_images')">成品图片</uni-th>
            <uni-th align="center" sortable @sort-change="sortChange($event, 'gif_url')" filter-type="search" @filter-change="filterChange($event, 'gif_url')">动图地址</uni-th>
            <uni-th align="center" sortable @sort-change="sortChange($event, 'operator_name')" filter-type="search" @filter-change="filterChange($event, 'operator_name')">操作员</uni-th>
            <uni-th align="center">操作</uni-th>
          </uni-tr>
          <uni-tr v-for="(item,index) in data" :key="index">
            <uni-td align="center">{{item._id}}</uni-td>
            <uni-td align="center">
              <uni-dateformat :threshold="[0, 0]" :date="item.create_date"></uni-dateformat>
            </uni-td>
            <uni-td align="center">{{item.template_id}}</uni-td>
            <uni-td align="center">{{item.photo_count}}</uni-td>
            <uni-td align="center">
              <view class="image-preview-container">
                <view v-if="item.photos && item.photos.length" class="image-grid">
                  <view v-for="(photo, photoIndex) in item.photos" :key="photoIndex" class="image-item">
                    <image 
                      :src="photo.thumbnail_url" 
                      mode="aspectFill" 
                      class="thumbnail"
                      @click="previewImage(item.photos, photoIndex)"
                    />
                  </view>
                </view>
                <text v-else>暂无图片</text>
              </view>
            </uni-td>
            <uni-td align="center">
              <view class="image-preview-container">
                <view v-if="item.result_images && item.result_images.length" class="image-grid">
                  <view v-for="(image, imageIndex) in item.result_images" :key="imageIndex" class="image-item">
                    <image 
                      :src="image.thumbnail_url" 
                      mode="aspectFill" 
                      class="thumbnail"
                      @click="previewImage(item.result_images, imageIndex)"
                    />
                  </view>
                </view>
                <text v-else>暂无图片</text>
              </view>
            </uni-td>
            <uni-td align="center">{{item.gif_url}}</uni-td>
            <uni-td align="center">
              <template v-if="item.operator_id">
                {{getUserName(item.operator_id)}}
              </template>
              <template v-else>
                无操作员
              </template>
            </uni-td>
            <uni-td align="center">
              <view class="uni-group">
                <button @click="navigateTo('./edit?id='+item._id, false)" class="uni-button" size="mini" type="primary">修改</button>
                <button @click="confirmDelete(item._id)" class="uni-button" size="mini" type="warn">删除</button>
              </view>
            </uni-td>
          </uni-tr>
        </uni-table>
        <view class="uni-pagination-box">
          <uni-pagination show-icon :page-size="pagination.size" v-model="pagination.current" :total="pagination.count" @change="onPageChanged" />
        </view>
      </unicloud-db>
    </view>
  </view>
</template>

<script>
  import { enumConverter, filterToWhere } from '../../js_sdk/validator/a-tasks.js';

  // 添加numberRange函数定义
  function numberRange(start, end) {
    const range = []
    for (let i = start; i <= end; i++) {
      range.push(i)
    }
    return range
  }

  const db = uniCloud.database()
  // 表查询配置
  const dbOrderBy = '' // 排序字段
  const dbSearchFields = ['operator_id'] // 添加操作员ID到搜索字段
  const dbJoinType = 'leftJoin'  // 添加连接类型
  
  // 分页配置
  const pageSize = 20
  const pageCurrent = 1

  const orderByMapping = {
    "ascending": "asc",
    "descending": "desc"
  }

  export default {
    data() {
      return {
        collectionList: "a-tasks",
        query: '',
        where: '',
        orderby: dbOrderBy,
        orderByFieldName: "",
        selectedIndexs: [],
        options: {
          pageSize,
          pageCurrent,
          filterData: {
            "status_data": numberRange(0, 2),
            "status_index": null,
            "print_status_data": numberRange(0, 1),
            "print_status_index": null
          },
          ...enumConverter
        },
        imageStyles: {
          width: 64,
          height: 64
        },
        exportExcel: {
          "filename": "a-tasks.xls",
          "type": "xls",
          "fields": {
            "template_id": "template_id",
            "photo_count": "photo_count",
            "photos": "photos",
            "result_images": "result_images",
            "gif_url": "gif_url",
            "status": "status",
            "print_status": "print_status",
            "create_date": "create_date",
            "complete_date": "complete_date",
            "print_date": "print_date",
            "operator_id": "operator_id"
          }
        },
        exportExcelData: [],
        previewImages: [], // 当前预览的图片列表
        currentPreviewIndex: 0, // 当前预览的图片索引
        userNameMap: {}, // 用于存储用户ID和昵称的映射
      }
    },
    onLoad() {
      this._filter = {}
    },
    onReady() {
      this.$refs.udb.loadData()
    },
    methods: {
      onqueryload(data) {
        this.exportExcelData = data
        
        // 如果数据中有operator_id，查询对应的用户昵称
        if (data && data.length > 0) {
          // 收集所有不为空的operator_id
          const operatorIds = data.filter(item => item.operator_id).map(item => item.operator_id)
          
          if (operatorIds.length > 0) {
            // 查询用户信息
            const db = uniCloud.database()
            db.collection('uni-id-users')
              .where({
                _id: db.command.in(operatorIds)
              })
              .field('_id,nickname,username')
              .get()
              .then(res => {
                const users = res.result.data || []
                // 将用户信息添加到映射对象中
                this.userNameMap = {}
                users.forEach(user => {
                  this.userNameMap[user._id] = user.nickname || user.username || '未知用户'
                })
                
                // 强制更新视图
                this.$forceUpdate()
                
                // 打印日志 - 移动到这里，确保用户信息已经更新
                console.log('查询结果（用户信息更新后）：', data)
                if(data && data.length > 0) {
                  console.log('第一条数据（用户信息更新后）：', data[0])
                  console.log('操作员信息（用户信息更新后）：', {
                    operator_id: data[0].operator_id || '无操作员',
                    '完整数据': data[0],
                    '用户名映射': this.userNameMap
                  })
                }
              })
              .catch(err => {
                console.error('获取用户信息失败', err)
              })
          }
          
          // 这里是初始数据的日志，用户名可能还未更新
          console.log('初始查询结果：', data)
          console.log('初始第一条数据：', data[0])
          console.log('初始操作员信息：', {
            operator_id: data[0].operator_id || '无操作员',
            '完整数据': data[0]
          })
        }
      },
      getWhere() {
        const query = this.query.trim()
        if (!query) {
          return ''
        }
        const queryRe = new RegExp(query, 'i')
        return dbSearchFields.map(name => queryRe + '.test(' + name + ')').join(' || ')
      },
      search() {
        const newWhere = this.getWhere()
        this.where = newWhere
        this.$nextTick(() => {
          this.loadData()
        })
      },
      loadData(clear = true) {
        this.$refs.udb.loadData({
          clear
        })
      },
      onPageChanged(e) {
        this.selectedIndexs.length = 0
        this.$refs.table.clearSelection()
        this.$refs.udb.loadData({
          current: e.current
        })
      },
      navigateTo(url, clear) {
        // clear 表示刷新列表时是否清除页码，true 表示刷新并回到列表第 1 页，默认为 true
        uni.navigateTo({
          url,
          events: {
            refreshData: () => {
              this.loadData(clear)
            }
          }
        })
      },
      // 多选处理
      selectedItems() {
        var dataList = this.$refs.udb.dataList
        return this.selectedIndexs.map(i => dataList[i]._id)
      },
      // 批量删除
      delTable() {
        this.$refs.udb.remove(this.selectedItems(), {
          success:(res) => {
            this.$refs.table.clearSelection()
          }
        })
      },
      // 多选
      selectionChange(e) {
        this.selectedIndexs = e.detail.index
      },
      confirmDelete(id) {
        this.$refs.udb.remove(id, {
          success:(res) => {
            this.$refs.table.clearSelection()
          }
        })
      },
      sortChange(e, name) {
        this.orderByFieldName = name;
        if (e.order) {
          this.orderby = name + ' ' + orderByMapping[e.order]
        } else {
          this.orderby = ''
        }
        this.$refs.table.clearSelection()
        this.$nextTick(() => {
          this.$refs.udb.loadData()
        })
      },
      filterChange(e, name) {
        this._filter[name] = {
          type: e.filterType,
          value: e.filter
        }
        let newWhere = filterToWhere(this._filter, db.command)
        if (Object.keys(newWhere).length) {
          this.where = newWhere
        } else {
          this.where = ''
        }
        this.$nextTick(() => {
          this.$refs.udb.loadData()
        })
      },
      // 预览图片
      previewImage(images, index) {
        if (!images || !images.length) {
          console.log('没有图片可以预览')
          return
        }
        // 根据图片类型获取正确的URL
        this.previewImages = images.map(img => {
          if (!img) return ''
          return img.photo_url || img.url || img.image_url || img.thumbnail_url || ''
        }).filter(url => url)
        
        if (!this.previewImages.length) {
          console.log('没有可用的图片URL')
          return
        }
        
        this.currentPreviewIndex = Math.min(index, this.previewImages.length - 1)
        this.$refs.previewPopup.open()
      },
      // 关闭预览
      closePreview() {
        this.$refs.previewPopup.close()
      },
      // 处理预览swiper切换
      handleSwiperChange(e) {
        this.currentPreviewIndex = e.detail.current
      },
      // 根据用户ID获取用户名
      getUserName(userId) {
        return this.userNameMap[userId] || '未知用户'
      },
    }
  }
</script>

<style>
.image-preview-container {
  padding: 5px;
}

.image-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  justify-content: center;
}

.image-item {
  width: 60px;
  height: 60px;
  overflow: hidden;
  border-radius: 4px;
}

.thumbnail {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.preview-popup {
  background-color: rgba(0, 0, 0, 0.9);
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.preview-swiper {
  width: 100%;
  height: calc(100vh - 100px);
}

.preview-image {
  width: 100%;
  height: 100%;
}
</style>
